//
//  StatusCell.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/7/2.
//  Copyright © 2015年 yyz. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

protocol StatusCellDelegate: NSObjectProtocol {
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int)
}

let YZStatusForwardCellIdentifier = "YZStatusForwardCellIdentifier"
let YZStatusNormalCellIdentifier = "YZStatusNormalCellIdentifier"
private let YZPictureCellReuseIdentifier = "YZPictureCellReuseIdentifier"

class StatusCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    weak var photoDelegate: StatusCellDelegate?
    /// 转发微博标签
    var forwardLabel: UILabel?
    
    var status: Status? {
        didSet {
            
            // 转发文字
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            // 设置头像
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            // 设置认证图标
            vipIconView.image = status?.user?.verifiedImage
            // 设置会员图标
            memberIconView.image = status?.user?.mbImage
            
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 微博"
            contentLabel.text = status?.text
            
            let size = calcPictureViewSize(status!)
            
            topCons?.constant = size.viewSize.height == 0 ? 0 : 12
            widthCons?.constant = size.viewSize.width
            heightCons?.constant = size.viewSize.height
            pictureLayout.itemSize = size.itemSize
            
            pictureView.reloadData()
            
        }
    }
    
    class func cellIdentifier(status: Status) -> String {
        return status.retweeted_status != nil ? YZStatusForwardCellIdentifier : YZStatusNormalCellIdentifier
    }
    
    private func calcPictureViewSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize) {
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10

        let count = status.picURLs?.count ?? 0
        
        // 1.没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        
        // 2.一张图片
        if count == 1 {
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            return (image.size,image.size)
        }
        
        
        // 3.多张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        
        let rowCount = 3
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h),itemSize)
    }
    
    func rowHeight(status: Status) -> CGFloat{
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    
    // MARK: - dataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YZPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status?.picURLs![indexPath.item]
        
        return cell
    }
    
    func fullScreenFrame(photoIndex: Int) -> CGRect{
        
        let urlString = status?.picURLs![photoIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        
        let w = screenSize.width
        let h = w * scale
        var y: CGFloat = 0
        
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 照片索引只需要传递 `Int` 会简化调用方的使用
        
        
        let url = status!.largePicURLs![indexPath.item]
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, totalBytes) -> Void in
            
            let progress = CGFloat(bytes)/CGFloat(totalBytes)
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.iconView.progress = progress
            })
            
            }, completed: { [unowned self] (_, error, _, _, _) -> Void in
                print(error)
                self.photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
            })
        
    }
    
    func screenFrame(photoIndex: Int) -> CGRect {
        
        
        let indexPath = NSIndexPath(forItem: photoIndex, inSection: 0)
        
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        
        return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        preparePictureView()
        
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 12))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: -12, y: 12))        
    }
    
    func recordPictureViewCons(cons: [NSLayoutConstraint]){
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)

    }
    
    private func preparePictureView() {
        
        pictureView.backgroundColor = UIColor.lightGrayColor()
        pictureView.dataSource = self
        pictureView.delegate = self
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: YZPictureCellReuseIdentifier)
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 空间的懒加载
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    lazy var vipIconView: UIImageView = UIImageView(image:UIImage(named: "avatar_grassroot"))
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, multiLines: true)
    
    // 图像视图 - UICollectionView
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    // 页脚视图 
    lazy var footerView: StatusFooterView = StatusFooterView()
    
    // 约束
    var widthCons: NSLayoutConstraint?
    var heightCons: NSLayoutConstraint?
    var topCons: NSLayoutConstraint?

    

}

// 配图cell
class StatusPictureCell: UICollectionViewCell {
    
    var imageURL:NSURL? {
        didSet{
            iconView.progress = 0
            iconView.sd_setImageWithURL(imageURL)
            gifIconView.hidden = !(imageURL?.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        addSubview(iconView)
        iconView.ff_Fill(self)
        addSubview(gifIconView)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView: YZImageView = YZImageView()
    private lazy var gifIconView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.hidden = true
        
        return iv
        }()
}

class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commentBtn: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)
}
